package week.six;

import java.nio.*;

import javax.microedition.khronos.opengles.GL10;

public class Square {

	public Vec2 position = new Vec2(0,0);
	public Vec3 rotation = new Vec3(0,0,0);
	private float width = 1;
	private float height = 1;
	
	private FloatBuffer vertexBuffer;
	private FloatBuffer colourBuffer;
	
	private void setVertices() {
		vertices = new float[] {
			-width,	 height,	0,
			 width,	 height,	0,
			-width,	-height,	0,
			 width,	-height,	0
		};
	}
	
	private float vertices[];
	
	private float colours[] = {
		1.0f, 0.0f, 0.0f, 1.0f,	// Red
		0.0f, 1.0f, 0.0f, 1.0f,	// Blue
		0.0f, 0.0f, 1.0f, 1.0f,	// Green
		1.0f, 1.0f, 0.0f, 1.0f	// Yellow
	};
	
	public Square(Vec2 position, float width, float height) {
		this.position = position;
		this.width = width/2;
		this.height = height/2;
		setVertices();
		
		ByteBuffer bytebuf = ByteBuffer.allocateDirect(vertices.length * 4);
		bytebuf.order(ByteOrder.nativeOrder());
		vertexBuffer = bytebuf.asFloatBuffer();
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);
		bytebuf = ByteBuffer.allocateDirect(colours.length * 4);
		bytebuf.order(ByteOrder.nativeOrder());
		colourBuffer = bytebuf.asFloatBuffer();
		colourBuffer.put(colours);
		colourBuffer.position(0);
	}
	
	public void draw(GL10 gl) {
		gl.glTranslatef(position.x, position.y, 0);
		gl.glRotatef(rotation.x, 1, 0, 0);
		gl.glRotatef(rotation.y, 0, 1, 0);
		gl.glRotatef(rotation.z, 0, 0, 1);
		gl.glFrontFace(GL10.GL_CW);
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
		gl.glColorPointer(4, GL10.GL_FLOAT, 0, colourBuffer);
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
		gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
	}
	
	public void setColours(float colours[]) {
		this.colours = colours;
		ByteBuffer bytebuf = ByteBuffer.allocateDirect(vertices.length * 4);
		bytebuf = ByteBuffer.allocateDirect(this.colours.length * 4);
		bytebuf.order(ByteOrder.nativeOrder());
		colourBuffer.put(this.colours);
		colourBuffer.position(0);
	}
}
